<?php

class Buy extends Controller {

	function index($selected_user_id = null)
	{
		global $VALUTA;
		$users = $this->MUser->getChildrenAndMe(Auth::$user_id);
		$root = $this->MUser->getRoot();
		$me = $this->MUser->get(Auth::$user_id);
		if($root['id'] != Auth::$user_id && !$me['can_oper'])
		{
			unset($users[Auth::$user_id]);
		}
		$root['children'] = $this->MUser->getMyStructure($root['id']);

		$kurses = $this->MKurs->getList();
		$kurses_date = array();
		foreach($kurses as $kurs)
		{
			$kurses_date[$kurs['date']][intval($kurs['percent'])] = array('buy' => floatval($kurs['buy']));
		}

		$users_l = array();
		$users_des = array();
		foreach($users as $u)
		{
			$users_l[$u['id']] = $u['lgota'] ? true : false;
			$users_des[$u['id']] = $this->MUser->getDateUpLevel($u['id']);
		}

		$my_scheta = $this->MSchet->getList(array('user_id' => Auth::$user_id));
		foreach($my_scheta as $k => $s)
		{
			$my_scheta[$k]['name'] .= " ".$VALUTA[$s['valuta']];
		}

		$selected_user_id = intval($selected_user_id);

		$this->load->view('head', array());
		$this->load->view('oper/buy', array('users' => $users, 'users_l' => $users_l, 'kurses' => $kurses_date, 'users_des' => $users_des, 'root' => $root, 'my_scheta' => $my_scheta, 'selected_user_id' => $selected_user_id));
		$this->load->view('foot');
	}

	function save()
	{
		global $VALUTA, $ALLOWED_FILES;
		$user_id = intval($_POST['user_id']);
		if(!$this->MUser->isCanOper($user_id))
		{
			return;
		}
		if($user_id == Auth::$user_id)
		{
			$root = $this->MUser->getRoot();
			$me = $this->MUser->get(Auth::$user_id);
			if($root['id'] != Auth::$user_id && !$me['can_oper'])
			{
				return;
			}
		}
		$date = dateToDb($_POST['year']."-".$_POST['month']."-".$_POST['day']);
		$user = $this->MUser->get($user_id);

/* Добавление платежа */
		$platezh_id = intval($_POST['platezh_id']);
		if($platezh_id == -1)
		{
			$platezh_id = 0;
		}
		elseif($platezh_id == 0) 
		{
			$schet_id = intval(@$_POST['platezh_schet_id']);
			$schet = $this->MSchet->get($schet_id);
			if(@$schet['id'])
			{
				$platezh_from_date = $date;
				$platezh_to_date = $date;
				$platezh_type = 'buy';
				$platezh_from_user_id = $user['id'];
				$platezh_people = null;
				if($schet['user_id'] != Auth::$user_id)
				{
					$platezh_type = 'buy.drugoy';
					$platezh_from_user_id = 0;
					$platezh_people = $user['fio'];
				}
				$save_platezh = array(
					'schet_id' => $schet['id'],
					'from_date' => $platezh_from_date,
					'to_date ' => $platezh_to_date,
					'summ' => round(getFloat(@$_POST['platezh_summ']), 2),
					'valuta' => @$_POST['platezh_valuta'],
					'komiss' => round(getFloat(@$_POST['platezh_komiss']), 2),
					'type' => $platezh_type,
					'from_user_id' => $platezh_from_user_id,
					'to_user_id' => $schet['user_id'],
					'people' => $platezh_people,
					'comment' => trim($_POST['dop']),
				);
			}
			for($i = 1; $i <= 5; $i++)
			{
				if(@$_FILES['file'.$i]['name'] && is_uploaded_file($_FILES['file'.$i]['tmp_name']))
				{
					$ex = strtolower(end(explode(".", $_FILES['file'.$i]['name'])));
					if(in_array($ex, $ALLOWED_FILES))
					{
						$filename = Auth::$user_id."_".md5(microtime()).".".$ex;
						if(move_uploaded_file($_FILES['file'.$i]['tmp_name'], UPLOAD_PATH.$filename))
						{
							$save_platezh['file'.$i] = $filename;
						}
					}
					else
					{
						$this->session->set_flashdata('system_error', 'Вы загрузили запрещённый тип файла: '.$_FILES['file'.$i]['name'].". Он не добавился к платежу.");
					}
					$save_platezh['file'.$i.'_comment'] = trim($_POST['file'.$i.'_comment']) == 'Комментарий' ? null : trim($_POST['file'.$i.'_comment']);
				}
			}
			if(@$save_platezh['summ'])
			{
				$this->MPlatezh->save($save_platezh, $platezh_id);
			}
		}

/* Сохранение покупки */
		$percent = getPercentByType($_POST['mavro_type_buy'], @$_POST['sverh'], $user, $date);
		$bonus = @$_POST['is_bonus'] ? 1 : 0;
		$type = $_POST['mavro_type_buy'] == 'week' ? 'week' : (@$_POST['is_bonus'] ? $_POST['bonus_type'] : 'buy');
		$user_is_lgota = $this->MUser->isLgota($user, $date, $type);
		$depo = getDepoMonth($user_is_lgota, $percent);
		$save = array(
			'user_id' => $user_id,
			'platezh_id' => $platezh_id,
			'date' => $date,
			'type' => $type,
			'bonus' => $bonus,
			'summ' => round(getFloat($_POST['summ_buy']), 4),
			'valuta' => trim($_POST['valuta']),
			'percent' => $percent,
			'depo' => $depo,
			'mavro_valuta' => $_POST['mavro_type_buy'] == 'week' ? trim($_POST['valuta']) : trim($_POST['mavro_valuta']),
			'hranen' => trim($_POST['hranen']),
			'dop' => trim($_POST['dop']),
			'_tmp_is_bonus' => intval(@$_POST['is_bonus']),
			'_tmp_bonus_type' => trim($_POST['bonus_type']),
			'_tmp_add_ref' => intval(@$_POST['add_ref']),
			'_tmp_ref_summ' => getFloat($_POST['ref_summ']),
			'_tmp_add_des' => intval(@$_POST['add_des']),
			'_tmp_des_summ' => getFloat($_POST['des_summ']),
			'_tmp_add_ng' => intval(@$_POST['add_ng']),
			'_tmp_ng_summ' => getFloat(@$_POST['ng_summ']),
		);
		if($_POST['mavro_type_buy'] != 'week')
		{
			$save['kurs'] = $this->MKurs->getKurs($save['date'], $percent, 'buy');
			$save['kurs_valuta'] = $save['mavro_valuta'] == $save['valuta'] ? 1 : getFloat(@$_POST['kurs_valuta']);
			$save['kurs_valuta'] = $save['kurs_valuta'] > 0 ? $save['kurs_valuta'] : 1;
			
			$save['mavro'] = @$_POST['kurs_valuta_reverse'] ? ($save['summ'] / $save['kurs_valuta'] / $save['kurs']) : ($save['summ'] * $save['kurs_valuta'] / $save['kurs']);
			$save['mavro'] = round($save['mavro'], 4);
			$save['ostatok'] = $save['mavro'];
		}
		$oper_id = 0;
		$this->MOper->save($save, $oper_id);
		$oper_new = $save;
		$oper_new['id'] = $oper_id;

		$i = 0;
		$des_id = Auth::$user_id;
		$this->load->library('phpmailer');
		$this->load->model('MSetting');
		$me = $this->MUser->get(Auth::$user_id);
		while($des_id && $i < 20)
		{
			$i++;
			$des_id = $this->MUser->getDesyatnikId($des_id, date("Y-m-d"));
			if($des_id)
			{
				$setting_des = $this->MSetting->getMe($des_id);
				if($setting_des['send_email_more'] > 0 && $save['summ'] >= $setting_des['send_email_more'])
				{
					$des = $this->MUser->get($des_id);
					$mail = new PHPMailer(); 
					$mail->IsHTML(true);    
					$mail->Subject = "В \"МММАНКе\" проведена операция на сумму ".$save['summ']." ".$VALUTA[$save['valuta']];
					$mail->Body = "Десятник: ".$me['fio']." (".$me['email'].")<br>Участник: ".$user['fio']." (".$user['email'].")<br>Сумма: ".$save['summ']." ".$VALUTA[$save['valuta']]."<br><br><a href='".base_url()."oper/?u[]=".$me['id']."&inc_des[]=".$me['id']."&t[]=buy&t[]=ng&t[]=ref&t[]=week&t[]=sell&t[]=l*' target=_blank>Посмотреть</a>";
					$mail->AddAddress($des['email']);
					$mail->Send();
				}
			}
		}


		$this->load->library('Operation');
		if($save['type'] == 'buy' && $save['bonus'] == 0)
		{

/* Начисление новогоднего бонуса */
/* Начисление патриотического или арестанского бонуса */
			if(@$_POST['add_ng'] && @$_POST['ng_summ'])
			{
				$this->operation->addNgBonus($oper_new, getFloat(@$_POST['ng_summ']));

				if($save['date'] >= PATRIOT_BONUS_BEGIN && $save['date'] <= PATRIOT_BONUS_END)
				{
					$this->operation->addPatriotBonus($oper_new, getFloat(@$_POST['ng_summ']));
				}
				elseif($save['date'] >= AREST_BONUS_BEGIN && $save['date'] <= AREST_BONUS_END)
				{
					if($this->MOper->getCount(array('type' => 'buy', 'bonus' => 0, 'user_id' => $save['user_id'], 'date>=' => PATRIOT_BONUS_BEGIN, 'date<=' => PATRIOT_BONUS_END)))
					{
						$this->operation->addPatriotBonus($oper_new, getFloat(@$_POST['ng_summ']));
					}
					else
					{
						$this->operation->addArestBonus($oper_new, getFloat(@$_POST['ng_summ']));
					}
				}
			}
		

/* Начисление бонуса 8 марта - только для структуры "Медведь" */
			if(@$_POST['add_8marta'] && @$_POST['vos_marta_summ'])
			{
				$this->operation->add8MartaBonus($oper_new, getFloat($_POST['vos_marta_summ']));
			}
		
/* Начисление реферального бонуса */
			if(@$_POST['add_ref'] && @$_POST['ref_summ'])
			{
				$user = $this->MUser->get($save['user_id']);
				if($user['referer_email'])
				{
					$ref_user = $this->MUser->getFirstRow(array('email' => $user['referer_email']));
					if(@$ref_user['id'])
					{
						$ref_mavro_valuta = @$_POST['ref_to_depo'] ? @$_POST['ref_depo_valuta'] : null;
						$ref_type = @$_POST['ref_to_depo'] ? @$_POST['ref_depo_type'] : null;
						$ref_sverh = @$_POST['ref_to_depo'] ? intval(@$_POST['ref_depo_sverh']) : null;
						$this->operation->addRefBonus($oper_new, $ref_user, $user, getFloat($_POST['ref_summ']), $ref_mavro_valuta, $ref_type, $ref_sverh);
					}
				}
			}
		
/* Начисление бонуса десятника*/
			if(@$_POST['add_des'] && $_POST['des_summ'])
			{
				$summ = getFloat($_POST['des_summ']);
				$des_mavro_valuta = @$_POST['des_to_depo'] ? @$_POST['des_depo_valuta'] : null;
				$des_type = @$_POST['des_to_depo'] ? @$_POST['des_depo_type'] : null;
				$des_sverh = @$_POST['des_to_depo'] ? intval(@$_POST['des_depo_sverh']) : null;
				$this->operation->addAllBonusRukovod($oper_new, $summ, $des_mavro_valuta, $des_type, $des_sverh);
			}
		}

/* Если это начисление бонуса руководителя, то начисляем бонусы выше */
		if(substr($save['type'], 0, 2) == 'l*')
		{
			$summ = getFloat($_POST['des_summ']);
			$user_id = $save['user_id'];
			$t = str_replace("l", '', $save['type']);
			$i = strlen($t);
			while($user_id && $i < 20)
			{
				$i++;
				$level = str_repeat('*', $i);
				$user_id = $this->MUser->getDesyatnikId($user_id, $save['date']);
				if($user_id)
				{
					$this->operation->addBonusRukovod($oper_new, $summ, $level, $user_id, $oper_id);
				}
			}
		}

		redirect("oper/?last_oper=".$oper_new['id']);
	}


	
}

